#include "base/core/os/directory.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/limits.h>
#include <string.h>
#include <errno.h>
#include <string>
#include "base/core/os/string.h"
#include "base/core/os/debug.h"
#include "base/core/utility.h"
#include "base/core/com_define.h"

bool PathIsExist(const char * path) 
{
	MMO_ASSERT_ERROR(path, false, EINVAL);
	struct stat file_stat;
	if (lstat(path, &file_stat) == 0) return true;
	else return false;
}

bool MakeDirectory(const char * path, bool is_hide /*= false*/) 
{
	MMO_ASSERT(path);
	if (path == NULL) return false;

	std::string dir_path(path);
	std::string::size_type seg_offset = dir_path.rfind(MMO_PATH_SEPRATOR);

	if (seg_offset != dir_path.npos) 
	{
		std::string parent_path = dir_path.substr(0, seg_offset);
		if (!PathIsExist(parent_path.c_str())
			&& !MakeDirectory(parent_path.c_str(), is_hide)) 
		{
			return false;
		}
	}

	if (!PathIsExist(path) && mkdir(path, 0700) != 0) 
	{
		MMO_ASSERT(false);
		return false;
	}
	return true;
}

std::string WorkDiretory() 
{
	size_t len = 0;
	std::string str;
	str.resize(PATH_MAX);
	char *p = getcwd(const_cast<char *>(str.c_str()), PATH_MAX);
	if (p) len = strlen(p);
	str.resize(len);
	return str;
}
